<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="排查时间" prop="remarkSpare1">
        <el-date-picker
          v-model="queryParams.remarkSpare1"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择排查时间"
          style="width: 180px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="排查部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :show-count="true"
          placeholder="请选择排查部门"
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="排查人员" prop="createBy">
        <el-select
          v-model="queryParams.createBy"
          filterable
          placeholder="选择排查人员"
          style="width: 180px"
        >
          <el-option
            v-for="user in filteredUsers"
            :key="user.userId + ''"
            :label="user.nickName"
            :value="user.userId + ''"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="判定依据" prop="remark">
        <el-select
          v-model="queryParams.remark"
          filterable
          placeholder="选择判定依据"
          style="width: 180px"
        >
          <el-option
            v-for="content in allBasis"
            :key="content.id + ''"
            :label="content.basis"
            :value="content.id + ''"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['risk:inspection:staticadd']"
          >新增</el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['risk:inspection:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['risk:inspection:removeall']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['risk:inspection:staticexport']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!--    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange"  @row-dblclick="handleRowDblclick">-->

    <el-table
      v-loading="loading"
      :data="inspectionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="排查时间" align="center" prop="inspectionTime" />
      <el-table-column label="排查部门" align="center" prop="deptName" />
      <el-table-column label="排查人员" align="center" prop="createBy" />
      <el-table-column
        label="判定依据"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClick(scope.row)"
            ><u>{{ scope.row.basis }}</u></el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="清单数量" align="center" prop="num" />
      <el-table-column label="符合" align="center" prop="accordNum" />
      <el-table-column label="不符合" align="center" prop="unAccordNum" />
      <el-table-column label="不涉及" align="center" prop="unInvolvedNum" />
      <!--      <el-table-column label="依据标准" align="center" prop="source" :formatter="sourceFormat"/>-->
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <!--      <el-table-column label="排查情况" align="center" prop="remarkSpare" :formatter="remarkSpareFormat"/>-->
      <!--      <el-table-column label="备用1" align="center" prop="remarkSpare1" />-->
      <!--      <el-table-column label="备用2" align="center" prop="remarkSpare2" />-->
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['risk:inspection:edit']"-->
      <!--          >修改</el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['risk:inspection:remove']"-->
      <!--          >删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改重大隐患自查清单对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="900px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24">
            <el-form-item label="排查时间" prop="remarkSpare1">
              <el-date-picker
                clearable
                size="small"
                v-model="form.remarkSpare1"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择排查时间"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="排查部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择排查部门"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="排查人员" prop="createBy">
              <el-select
                v-model="form.createBy"
                filterable
                placeholder="选择排查人员"
                style="width: 100%"
              >
                <el-option
                  v-for="user in filteredUsers"
                  :key="user.userId + ''"
                  :label="user.nickName"
                  :value="user.userId + ''"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-for="(itme, index) in basisList">
          <el-divider content-position="center">{{ itme.basis }}</el-divider>
          <el-input style="width: 100%" v-model="itme.remark" v-if="false" />
          <el-input
            style="width: 100%"
            v-model="itme.inspectionTime"
            v-if="false"
          />
          <el-table
            :data="itme.contentList"
            :row-class-name="rowContentDetailIndex"
            @selection-change="handleReportOilDepotDetailSelectionChange"
            ref="contentDetail"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="序号"
              align="center"
              prop="index"
              width="50"
            />
            <el-table-column
              label="排查内容"
              prop="inspectionProject"
              header-align="center"
              v-if="false"
            />

            <el-table-column
              label="排查内容"
              prop="source"
              header-align="center"
            />

            <el-table-column
              label-class-name="text-center"
              label="排查情况"
              prop="remarkSpare2"
            >
              <template slot-scope="scope">
                <el-input
                  style="width: 100%; background-color: transparent"
                  type="textarea"
                  v-model="scope.row.remarkSpare2"
                  placeholder="请输入排查情况"
                />
              </template>
            </el-table-column>

            <el-table-column
              label-class-name="text-center"
              label="排查结果"
              prop="remarkSpare"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.remarkSpare"
                  placeholder="请选择排查结果"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in remarkSpareOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label-class-name="text-center"
              label="整改措施"
              prop="inspectionSituation"
            >
              <template slot-scope="scope">
                <el-input
                  type="textarea"
                  style="width: 100%"
                  v-model="scope.row.inspectionSituation"
                  placeholder="请输入整改措施"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStaticInspection,
  getInspection,
  delInspections,
  addAllInspection,
  updateInspection,
  exportInspection,
  optionselect,
  overtimeControl,
} from "@/api/risk/inspection";
import Treeselect from "@riophae/vue-treeselect";
import { treeselect } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCurrentUser, listUserNoPage } from "@/api/system/user";
import { allList } from "@/api/risk/content";
import { allBasis, listOption } from "@/api/risk/basis";

export default {
  name: "Inspection",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      rows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 重大隐患自查清单表格数据
      inspectionList: [],
      // 危险源ID字典
      sourceIdOptions: [],
      remarkSpareOptions: [],
      contentList: [],
      basisList: [],
      allBasis: [],
      // 部门树选项
      deptOptions: undefined,
      filteredUsers: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        remarkSpare1: null,
        deptId: null,
        createBy: null,
      },
      // 表单参数
      form: {
        remarkSpare1: null,
        deptId: null,
        createBy: null,
      },
      // 表单校验
      rules: {
        remarkSpare1: [
          { required: true, message: "排查时间不能为空", trigger: "blur" },
        ],
        inspectionProject: [
          { required: true, message: "发现项目不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "排查部门不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "排查人员不能为空", trigger: "blur" },
        ],
      },
      createBy: "",
      deptId: "",
    };
  },
  watch: {
    basisList: {
      handler(newVal) {
        localStorage.setItem("basisList", JSON.stringify(newVal));
        // console.log(333, newVal);
      },
      deep: true,
    },
    form: {
      handler(newVal) {
        localStorage.setItem("form", JSON.stringify(newVal));
        // console.log(66666, newVal);
      },
      deep: true,
    },
  },
  created() {
    this.getCurrentUser();
    this.getList();
    this.getTreeselect();
    this.getContent();
    this.getBasis();
    this.getallBasis();
    this.fetchUsers();
    this.getDicts("investigation_situation").then((response) => {
      this.remarkSpareOptions = response.data;
    });
  },
  methods: {
    /** 查询重大隐患自查清单列表 */
    getList() {
      this.loading = true;
      listStaticInspection(this.queryParams).then((response) => {
        this.inspectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      optionselect().then((response) => {
        this.sourceIdOptions = response.data;
      });
      this.overtime();
    },
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        // console.log('this.deptOptions:' + JSON.stringify(this.deptOptions))
      });
    },
    getCurrentUser() {
      let currentUser = this.$store.state.user;
      getCurrentUser(currentUser.userId).then((response) => {
        this.createBy = response.data.userId;
        this.deptId = response.data.deptId;
      });
    },
    fetchUsers() {
      this.loading = true;
      listUserNoPage().then((response) => {
        this.filteredUsers = response.rows;
        this.loading = false;
      });
    },
    getContent() {
      allList().then((response) => {
        this.contentList = response.data;
      });
      // console.log(this.contentList);
    },
    getallBasis() {
      listOption().then((response) => {
        this.allBasis = response.data;
      });
      // console.log(this.allBasis);
    },
    getBasis() {
      const basis = localStorage.getItem("basisList");
      if (basis) {
        this.basisList = JSON.parse(basis);
        // console.log(111, this.basisList);
      } else {
        allBasis().then((response) => {
          this.basisList = response.data;
          // console.log(222, this.basisList);
        });
      }
    },
    overtime() {
      overtimeControl().then((response) => {
        if (response.code === 200) {
        } else {
          this.msgError(response.msg);
        }
      });
    },
    sourceFormat(row, column) {
      return this.selectDictLabels(this.sourceIdOptions, row.source);
    },
    remarkSpareFormat(row, column) {
      return this.selectDictLabel(this.remarkSpareOptions, row.remarkSpare);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionTime: null,
        inspectionProject: null,
        inspectionSituation: null,
        source: null,
        remark: null,
        remarkSpare: null,
        remarkSpare1: null,
        remarkSpare2: null,
        createBy: null,
        createTime: null,
        deptId: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.rows = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // console.log(this.contentList);
      this.reset();
      const formData = localStorage.getItem("form");
      if (formData) {
        this.form = JSON.parse(localStorage.getItem("form"));
        // console.log(4444, this.form);
      } else {
        this.form.createBy = this.createBy + "";
        this.form.deptId = this.deptId;
        var now = new Date();
        var month = now.getMonth() + 1;
        var year = now.getFullYear();
        this.form.remarkSpare1 = year + "-" + month;
        // console.log(this.contentList);
        // console.log(5555, this.form);
      }

      this.open = true;
      this.title = "添加重大隐患自查清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInspection(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改重大隐患自查清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.validateDetailList({}, this.basisList, (error) => {
        if (error) {
          // 如果有错误，提示用户
          this.$message.error(error.message);
        } else {
          this.$refs["form"].validate((valid) => {
            if (valid) {
              this.form.basisList = this.basisList;
              if (this.form.id != null) {
                updateInspection(this.form).then((response) => {
                  localStorage.removeItem("basisList");
                  localStorage.removeItem("form");
                  this.from = null
                  this.basisList = null;
                  this.getBasis();
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addAllInspection(this.form).then((response) => {
                  localStorage.removeItem("basisList");
                  localStorage.removeItem("form");
                  this.from = null
                  this.basisList = null;
                  this.getBasis();
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const ids = row.id || this.ids;
      const param = [];
      for (let i = 0; i < this.rows.length; i++) {
        const row = this.rows[i];
        const params = {
          remarkSpare1: row.inspectionTime,
          deptId: row.deptId,
          createBy: row.userId,
          remark: row.remark,
        };
        param.push(params);
      }
      let obj = {};
      obj.basisList = param;
      this.$confirm("是否确认删除选中的重大隐患自查清单数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delInspections(obj);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有重大隐患自查清单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          // return exportInspection(queryParams);
          this.download(
            "/risk/inspection/exportStatic",
            {
              ...this.queryParams,
            },
            `重大隐患自查清单.xlsx`
          );
          this.exportLoading = false;
        })
        .then((response) => {
          // this.download(response.msg);
          // this.exportLoading = false;
        })
        .catch(() => {});
    },
    rowContentDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    handleReportOilDepotDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.contentDetail.clearSelection();
        this.$refs.contentDetail.toggleRowSelection(selection.pop());
      } else {
        this.contentDetail = selection;
      }
    },
    validateDetailList(rule, value, callback) {
      // if (!value || value.length === 0) {
      //   return callback(new Error('请至少添加一条明细'));
      // }
      for (let i = 0; i < value.length; i++) {
        let basis = value[i];
        // 遍历明细列表，逐一检查每个字段
        let name = basis.basis;
        let contents = basis.contentList;
        for (let i = 0; i < contents.length; i++) {
          let detail = contents[i];
          if (!detail.remarkSpare2) {
            return callback(
              new Error(name + "中序号 " + detail.index + " 排查情况不能为空")
            );
          }
          if (!detail.remarkSpare) {
            return callback(
              new Error(name + "中序号 " + detail.index + " 排查结果不能为空")
            );
          }
          if (detail.remarkSpare === "2") {
            if (!detail.inspectionSituation) {
              return callback(
                new Error(name + "中序号 " + detail.index + " 整改措施不能为空")
              );
            }
          }
        }
      }
      // 验证通过
      callback();
    },
    handleRowDblclick(row, event, column) {
      // 双击行时的处理逻辑
      // console.log("双击行:", row);
      this.$router.push({
        name: "InspectionDetail",
        params: {
          remarkSpare1: row.inspectionTime,
          deptId: row.deptId,
          createBy: row.userId,
        },
      });
    },
    handleClick(row) {
      console.log("点击判定依据:", row);
      this.$router.push({
        name: "InspectionDetail",
        params: {
          remarkSpare1: row.inspectionTime,
          deptId: row.deptId,
          createBy: row.userId,
          remark: row.remark,
        },
      });
    },
  },
};
</script>
